package com.jl.rule;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;

/**
 * 规则 值取余
 */
public class JLRuleValueRem<T extends Comparable<?>> implements PreciseShardingAlgorithm<T>, RangeShardingAlgorithm<T> {

    private String length;

    public JLRuleValueRem(String length) {
        this.length = length;
    }

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<T> preciseShardingValue) {
        T v = preciseShardingValue.getValue();
        Long value;
        if (v instanceof Long) {
            value = (Long) v;
        } else {
            String s = String.valueOf(v);
            if (s.indexOf(".") != -1) {
                s = s.substring(0, s.indexOf("."));
            }
            value = Long.valueOf(s);
        }
        int lengths = Integer.parseInt(length);
        for (String each : collection) {
            if (each.endsWith(Long.toString(value % lengths))) {
                return each;
            }
        }
        return null;
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<T> rangeShardingValue) {
        return collection;
    }
}
